﻿#include "server.h"
#include <QDebug>

Server::Server(QObject *parent) : QObject(parent)
{
    tcpServer = new QTcpServer(this);

    // 有新的连接时，触发信号槽
    connect(tcpServer,&QTcpServer::newConnection,this,&Server::onNewConnection);
}

void Server::startServer()
{
    if(tcpServer->listen(QHostAddress::Any,12345)) {
        qDebug() << "当前端口号为：12345" <<endl;
    } else {
        qDebug() << "监听失败！" <<endl;
        return;
    }
}

void Server::onNewConnection()
{
    QTcpSocket *clientSocket = tcpServer->nextPendingConnection();
    qDebug() << "下一个客户端连接：" << endl;

    // 为每个新连接创建一个新的线程
    ClientThread *clientThread = new ClientThread(clientSocket);
    clientThread->start();  // 启动线程
}

ClientThread::ClientThread(QTcpSocket *socket, QObject *parent)
    : QThread(parent), clientSocket(socket)
{
    connect(clientSocket, &QTcpSocket::readyRead, this, &ClientThread::onReadyRead);
    connect(clientSocket, &QTcpSocket::disconnected, this, &ClientThread::onDisconnected);
}

ClientThread::~ClientThread()
{
    clientSocket->deleteLater();
}

void ClientThread::run()
{
    qDebug() << "客户端线程启动！ 线程 ID:" << QThread::currentThreadId();  // 输出当前线程ID
    exec(); // 启动事件循环，处理socket的信号槽
}

void ClientThread::onReadyRead()
{
    QByteArray data = clientSocket->readAll();
    qDebug() << "线程" << QThread::currentThreadId() << ": 收到来自客户端的消息:" << data;

    // 将数据回传给客户端
    clientSocket->write("返回: " + data);
}

void ClientThread::onDisconnected()
{
    qDebug() << "线程：" << QThread::currentThreadId() << ": 客户端断开连接！";
    clientSocket->close();
    quit(); // 结束线程事件循环
}
